<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus"
import { phoneLoginApi, sendSmsApi } from "@@/apis/auth"
import { CircleCheck, Lock, Phone } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { useUserStore } from "@/pinia/stores/user"
import { routerConfig } from "@/router/config"

const userStore = useUserStore()
const router = useRouter()
const isLoading = ref(false)
const isSendingCode = ref(false)
const countdown = ref(0)
const loginForm = reactive({
  phoneNumber: "",
  verificationCode: ""
})

// 表单校验规则
const loginFormRules = reactive<FormRules>({
  phoneNumber: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1\d{10}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 6, max: 6, message: "验证码长度必须为6位", trigger: "blur" }
  ]
})

const loginFormRef = ref<FormInstance>()

// 发送验证码
async function sendVerificationCode() {
  try {
    // 验证手机号
    await loginFormRef.value?.validateField("phoneNumber")

    isSendingCode.value = true

    // 调用发送验证码接口
    const { code, message } = await sendSmsApi({
      phone: loginForm.phoneNumber
    })

    // 检查接口返回状态
    if (code === 200) {
      ElMessage.success(message)
      // 开始倒计时
      startCountdown()
    } else {
      ElMessage.error(message)
    }
  } catch (error: any) {
    // 如果是验证错误，不显示发送失败消息
    if (error?.message && !error.message.includes("验证码")) {
      ElMessage.error(error?.message || "发送验证码失败，请重试")
    }
  } finally {
    isSendingCode.value = false
  }
}

// 开始倒计时
function startCountdown() {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 登录
async function handleLogin() {
  try {
    // 1️⃣ 前端验证层：表单格式验证
    const valid = await loginFormRef.value?.validate()
    if (!valid) return

    isLoading.value = true

    // 2️⃣ 接口调用层：网络请求
    const { code, data, message } = await phoneLoginApi({
      phone: loginForm.phoneNumber,
      code: loginForm.verificationCode
    })

    // 3️⃣ 业务逻辑层：状态码判断
    if (code === 200) {
      // 登录成功
      ElMessage.success(message || "登录成功")

      // 保存用户信息和token
      if (data) {
        // 设置token
        userStore.setToken(data.token)
        // userStore.setToken("0217849f-967a-4e90-a2de-7f60e8d7d618")

        // 直接设置用户信息，不需要调用getInfo
        if (data.userInfo) {
          // 先设置默认角色
          // userStore.roles = ["DEFAULT_ROLE"]
          userStore.roles = routerConfig.defaultRoles
          // 设置用户名
          userStore.username = data.userInfo.nickname ?? ""
          // 设置完整用户信息
          userStore.userInfo = data.userInfo
        }
      }

      // 跳转到首页
      router.push("/")
    } else {
      // 业务失败
      ElMessage.error(message || "登录失败，请重试")
    }
  } catch (error: any) {
    // 4️⃣ 异常处理层：网络/系统异常
    ElMessage.error(error?.message || "登录失败，请重试")
  } finally {
    // 5️⃣ 清理层：状态重置
    isLoading.value = false
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-content">
      <div class="app-info">
        <div class="logo">
          <img src="/pocket-ai-logo.png" alt="" class="logo-icon">
        </div>
        <h1 class="title">分销管理系统</h1>
        <p class="subtitle">Pocket Ai 后台管理</p>
      </div>

      <!-- Login form -->
      <div class="login-box">
        <h2 class="form-title">手机快速登录</h2>
        <p class="form-subtitle">输入手机号获取验证码，登录即注册</p>
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginFormRules"
          label-position="top"
          size="large"
        >
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input
              v-model="loginForm.phoneNumber"
              placeholder="请输入手机号码"
              clearable
              :prefix-icon="Phone"
            />
          </el-form-item>

          <el-form-item label="验证码" prop="verificationCode">
            <div class="verification-code">
              <el-input
                v-model="loginForm.verificationCode"
                placeholder="请输入6位验证码"
                maxlength="6"
              />
              <el-button
                type="primary"
                plain
                :loading="isSendingCode"
                :disabled="countdown > 0"
                @click="sendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <el-button type="primary" class="login-button" :loading="isLoading" @click="handleLogin">
            立即登录
          </el-button>
        </el-form>

        <!-- Security info -->
        <div class="security-info">
          <el-icon><Lock /></el-icon>
          <div class="security-text">
            <p class="security-title">
              安全保障
            </p>
            <p class="security-desc">我们采用银行级加密技术保护您的信息安全，验证码仅用于身份验证，不会透露给第三方</p>
          </div>
        </div>

        <!-- Features -->
        <div class="features">
          <p class="features-title">登录后即可享受</p>
          <div class="features-list">
            <div class="feature-item">
              <el-icon color="#67C23A">
                <CircleCheck />
              </el-icon>
              <span>AI智能创作</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A">
                <CircleCheck />
              </el-icon>
              <span>自动发布管理</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A">
                <CircleCheck />
              </el-icon>
              <span>数据分析报表</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A">
                <CircleCheck />
              </el-icon>
              <span>多平台支持</span>
            </div>
          </div>
        </div>

        <!-- Agreement -->
        <div class="agreement">
          <p>登录即表示同意我们的 <a href="#">《用户协议》</a> 和 <a href="#">《隐私政策》</a></p>
        </div>
      </div>

      <!-- Footer -->
      <div class="login-footer">
        <p>遇到问题? 联系客服微信号：pocketai_service</p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f7ff;
  padding: 0;
  overflow: hidden;
}

.login-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 420px; /* 减小最大宽度 */
  width: 100%;
}

.app-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px; /* 减小间距 */

  .logo {
    width: 60px; /* 减小logo尺寸 */
    height: 60px;
    background-color: #4080ff;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 12px; /* 减小间距 */

    .logo-icon {
      width: 100%;
      height: 100%;
    }
  }

  .title {
    font-size: 20px; /* 减小字体大小 */
    font-weight: 600;
    margin: 0 0 4px;
    color: #333;
  }

  .subtitle {
    font-size: 13px; /* 减小字体大小 */
    color: #666;
    margin: 0;
  }
}

.login-box {
  width: 100%;
  background-color: #fff;
  border-radius: 10px; /* 减小圆角 */
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  padding: 18px 25px; /* 减小内边距 */
  box-sizing: border-box;

  .form-title {
    font-size: 17px; /* 减小字体大小 */
    font-weight: 600;
    text-align: center;
    margin: 0 0 4px;
  }

  .form-subtitle {
    font-size: 13px; /* 减小字体大小 */
    color: #666;
    text-align: center;
    margin: 0 0 20px; /* 减小间距 */
  }

  :deep(.el-form-item__label) {
    padding-bottom: 3px;
    line-height: 1;
    font-size: 13px; /* 减小字体大小 */
    color: #333;
  }

  :deep(.el-form-item) {
    margin-bottom: 25px; /* 减小表单项间距 */
  }

  :deep(.el-input__wrapper) {
    background-color: #f5f7fa;
    border-radius: 4px;
    box-shadow: none;
    border: 1px solid transparent;
    height: 38px; /* 减小输入框高度 */

    &:hover,
    &:focus,
    &.is-focus {
      box-shadow: none;
      border-color: #dcdfe6;
    }
  }

  .verification-code {
    display: flex;
    gap: 10px;
    width: 100%;

    :deep(.el-input) {
      flex: 3; /* 增加验证码输入框的比例 */
    }

    .el-button {
      white-space: nowrap;
      height: 38px; /* 减小按钮高度 */
      padding: 0 12px; /* 减小按钮内边距 */
      flex: 1;
      font-size: 13px; /* 减小按钮字体大小 */
    }
  }

  .login-button {
    width: 100%;
    height: 40px; /* 减小按钮高度 */
    font-size: 15px; /* 减小字体大小 */
    margin-bottom: 15px;
    border-radius: 6px;
    background-color: #6698ff;
    border-color: #6698ff;

    &:hover,
    &:focus {
      background-color: #5a89f1;
      border-color: #5a89f1;
    }
  }
}

.security-info {
  display: flex;
  align-items: flex-start;
  background-color: #f0f7ff;
  padding: 12px; /* 减小内边距 */
  border-radius: 8px;
  margin-bottom: 18px; /* 减小间距 */

  .el-icon {
    color: #4080ff;
    font-size: 16px; /* 减小图标大小 */
    margin-right: 8px;
    margin-top: 2px;
  }

  .security-text {
    flex: 1;

    .security-title {
      font-size: 13px; /* 减小字体大小 */
      font-weight: 500;
      margin: 0 0 4px;
      color: #333;
    }

    .security-desc {
      font-size: 11px; /* 减小字体大小 */
      color: #666;
      margin: 0;
      line-height: 1.4;
    }
  }
}

.features {
  margin-bottom: 18px; /* 减小间距 */

  .features-title {
    font-size: 13px; /* 减小字体大小 */
    text-align: center;
    color: #333;
    margin-bottom: 12px; /* 减小间距 */
  }

  .features-list {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px; /* 减小间距 */

    .feature-item {
      display: flex;
      align-items: center;
      font-size: 13px; /* 减小字体大小 */

      .el-icon {
        margin-right: 6px;
        font-size: 14px; /* 减小图标大小 */
      }
    }
  }
}

.agreement {
  text-align: center;
  font-size: 11px; /* 减小字体大小 */
  color: #666;
  margin-bottom: 8px; /* 减小间距 */

  a {
    color: #4080ff;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.login-footer {
  text-align: center;
  margin-top: 12px; /* 减小间距 */
  font-size: 11px; /* 减小字体大小 */
  color: #999;
}
</style>
